package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;

/**
 * @Auther: you
 * @Date: 2021/05/26/20:06
 * @Description:
 */
@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        User user = userService.queryUserByToken(token);
        //token令牌校验成功，存储用户信息
        if (!(user == null)) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(user.getId());
            userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
            userInfo.setNickName(param.get("nickname"));
            userInfo.setBirthday(param.get("birthday"));
            userInfo.setCity(param.get("city"));
            return this.userInfoMapper.insert(userInfo) == 1;
        }

        //失败，返回false
        return false;
    }

    public Boolean saveUserLogo(MultipartFile file, String token) {
        //1.token令牌校验
        User user = userService.queryUserByToken(token);
        //token令牌校验失败，返回false
        if (user == null) {
            return false;
        }

        //2.人像识别
//        try {
//            //校验图片是否是人像，如果不是人像就返回false
//            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
//            if (!b) {
//                return false;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //3.头像上传阿里云
        PicUploadResult picUploadResult = picUploadService.upload(file);
        //上传失败，返回false
        if (StringUtils.isEmpty(picUploadResult.getName())){
            return false;
        }

        //4.上传成功，将图像访问url 保存在数据库中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(picUploadResult.getName());

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",user.getId());

        //更新结果，并返回更新结果
        return userInfoMapper.update(userInfo,queryWrapper)==1;

    }
}
